import threading
import time
from queue import Queue, Empty
# 通过安全的队列来通信.

list_status = False


class GetListHtml(threading.Thread):

    def __init__(self, url_queue: Queue):
        super(GetListHtml, self).__init__()
        self.url_queue = url_queue

    def run(self):
        print('开始获取列表页')
        try:
            for i in range(10):
                time.sleep(2)  # 模拟网络请求.
                url = f'www.yrx.com/{i}'
                self.url_queue.put(url)
                print('已经获取到获取列表页')
        finally:
            global list_status
            list_status = True


class GetDetailHtml(threading.Thread):

    def __init__(self, url_queue: Queue):
        super(GetDetailHtml, self).__init__()
        self.url_queue = url_queue

    def run(self):
        print('开始获取详情页')
        while True:
            try:
                url = self.url_queue.get(timeout=1)
                print(f'已经获取到获取详情页-{url}')
                time.sleep(1)  # 模拟网络请求.
            except Empty:  # 想一个办法, 让程序知道生产者已经结束了.
                global list_status
                print(list_status)
                if list_status:
                    print('详情页已抓完')
                    break


if __name__ == '__main__':
    # start_time = time.time()
    url_queue = Queue(100)
    t1 = GetListHtml(url_queue)
    t2 = GetDetailHtml(url_queue)
    t3 = GetDetailHtml(url_queue)
    t1.start()
    t2.start()
    t3.start()
    # t1.join()
    # t2.join()
    # t3.join()
    # url_queue.join()
    # join: 阻塞队列. 在主线程阻塞.
    # join里有一个计数器, 这一个计数器会在put的时候加1. 在每一次task_done的时候减1.
    # 当这个计数器是0的时候. 它会释放这个阻塞.
    # print(time.time() - start_time)